package com.coollang.smartbra.activity;


import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.coollang.smartbra.R;
import com.coollang.smartbra.base.MyApplication;
import com.coollang.smartbra.base.NewActionFragment;
import com.coollang.smartbra.beans.NewActionData;
import com.coollang.smartbra.constant.Constants;
import com.coollang.smartbra.constant.ResourceList;
import com.coollang.smartbra.dialog.RunSetDialog;
import com.coollang.smartbra.eventbus.CommonEvent;
import com.coollang.smartbra.fragment.NewActionCountFragment;
import com.coollang.smartbra.fragment.NewActionTimeFragment;
import com.coollang.smartbra.interfaces.ActionType;
import com.coollang.smartbra.interfaces.NewActionView;
import com.coollang.smartbra.presenter2.NewActionPresenter;
import com.coollang.smartbra.utils.ActivitySwitcher;
import com.coollang.smartbra.utils.DisplayUtils;
import com.coollang.smartbra.utils.TranslucentSystemBarUtils;
import com.inuker.bluetooth.library.Code;

import java.io.IOException;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

/**
 * @author: Timmy
 * @data: 2017/12/12
 * @Fuction:
 */
public class NewActionActivity extends AbstractMvpActivity<NewActionView, NewActionPresenter> implements NewActionView {

    private static final String TAG = "NewActionActivity";
    @BindView(R.id.status_bar)
    View mStatusBar;
    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.iv_right)
    ImageView mIvRight;
    @BindView(R.id.content)
    FrameLayout mContent;
    @BindView(R.id.action_frame_videoview)
    VideoView mVideoView;
    @BindView(R.id.action_frame)
    FrameLayout mFLAction;
    @BindView(R.id.linearlayout_title)
    LinearLayout mLayoutTitle;
    @BindView(R.id.heart_imag)
    ImageView mIvHeartTooHeight;
    @BindView(R.id.video_background)
    View mVideoBackGround;
    private int mActionType;
    private NewActionFragment mFragment;
    private MediaPlayer mMediaPlayer;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_action);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        TranslucentSystemBarUtils.showChenJinZhuangTaiLan(mStatusBar, this, mContent);

        initView();
        initData();
    }

    @Override
    protected NewActionPresenter createPresenter() {
        return new NewActionPresenter();
    }

    @Override
    protected void onStart() {
        super.onStart();
        startVideo();
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopVideo();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        detachMediaPlayer();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (getScreenOrientation() == Configuration.ORIENTATION_LANDSCAPE) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                return false;
            } else if (getPresenter().isSporting()) {
                Toast.makeText(this, "请结束当前运动", Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private void initView() {
        Intent intent = getIntent();
        if (intent != null) {
            mActionType = intent.getIntExtra(Constants.TYPE, 1);
            // 设置标题
            mTvTitle.setText(ResourceList.ACTION_NAME_LIST[mActionType]);
            mTvTitle.setTextColor(ContextCompat.getColor(this, R.color.black_666));
        }
        mIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getPresenter().isSporting()) {
                    Toast.makeText(NewActionActivity.this, "请结束当前运动", Toast.LENGTH_SHORT).show();
                } else {
                    finish();
                }
            }
        });

        //设置下面布局
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.action_frame, getFragment(mActionType))
                .commit();
    }

    /**
     * 获取计时或者计数视频
     */
    private Fragment getFragment(int actionType) {
        switch (Constants.ACTION_NAME_ID1[actionType]) {
            case ActionType.PBZC:
                mFragment = new NewActionTimeFragment();
                break;
            default:
                mFragment = new NewActionCountFragment();
                break;
        }
        Bundle bundle = new Bundle();
        bundle.putInt(Constants.TYPE, actionType);
        mFragment.setArguments(bundle);

        getPresenter().setListener(mFragment);
        return mFragment;
    }

    private void initData() {
        NewActionPresenter presenter = getPresenter();
        if (presenter != null) {
        }
    }

    @OnClick({R.id.iv_right, R.id.iv_unwind})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_right:
                new RunSetDialog(this, false, mIvRight).show();
                break;
            case R.id.iv_unwind:
                // 横竖屏切换
                if (getScreenOrientation() == Configuration.ORIENTATION_PORTRAIT) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    return;
                }
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                break;
            default:
                break;
        }
    }

    public void onEventMainThread(CommonEvent event) {
        if (event.type == CommonEvent.START) {
            if (event.what == CommonEvent.REQUESTSUEECCD) {
                // 运动开始了
                mIvBack.setVisibility(View.GONE);
                getPresenter().startAction();
            }
        }
    }

    /**
     * 横竖屏切换
     */
    private int getScreenOrientation() {
        return getResources().getConfiguration().orientation;
    }

    /**
     * 开始播放视频
     */
    private void startVideo() {
        if (mVideoView != null && !mVideoView.isPlaying()) {
            mVideoView.setVideoURI(getPresenter().getVideoPath(mActionType));
            mVideoView.start();
            mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    mVideoView.start();
                }
            });

            if (mVideoBackGround.getVisibility() == View.VISIBLE) {
                mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mediaPlayer) {
                        mediaPlayer.setOnInfoListener(new MediaPlayer.OnInfoListener() {
                            @Override
                            public boolean onInfo(MediaPlayer mp, int what, int extra) {
                                if (what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) {
                                    mVideoBackGround.setVisibility(View.GONE);
                                }
                                return true;
                            }
                        });
                    }
                });
            }
        }
    }

    /**
     * 暂停播放视频
     */
    public void stopVideo() {
        if (mVideoView != null) {
            if (mVideoView.isPlaying()) {
                mVideoView.stopPlayback();
            }
        }
    }

    public NewActionFragment getFragment() {
        return mFragment;
    }

    /**
     * ========================================================================================
     * 视频播放横竖屏切换问题
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        int value = getScreenOrientation();
        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_VISIBLE;
        if (value == Configuration.ORIENTATION_LANDSCAPE) {
            // 全屏,隐藏状态栏
            uiOptions = View.INVISIBLE;
            mFLAction.setVisibility(View.GONE);
            mLayoutTitle.setVisibility(View.GONE);
            setScreenLayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        } else if (value == Configuration.ORIENTATION_PORTRAIT) {
            // 半屏幕,显示状态栏
            uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
            mFLAction.setVisibility(View.VISIBLE);
            mLayoutTitle.setVisibility(View.VISIBLE);
            setScreenLayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DisplayUtils.dp2px(this, 424));
        }

        decorView.setSystemUiVisibility(uiOptions);
    }

    private void setScreenLayoutParams(int width, int height) {
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(width, height);
        if (width == ViewGroup.LayoutParams.MATCH_PARENT && height == ViewGroup.LayoutParams.MATCH_PARENT) {
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        }
        mVideoView.setLayoutParams(layoutParams);
        mVideoView.requestFocus();
    }
    /**
     * ========================================================================================
     */

    /**
     * 运动结束
     *
     * @param actionDatas
     */
    public void finishAction(ArrayList<NewActionData> actionDatas) {
        getPresenter().finishAction(actionDatas);
    }

    @Override
    public int getActionType() {
        return mActionType;
    }

    @Override
    public void showFinishDialog() {
        AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.setMessage(getString(R.string.no_countortimedata));
        dialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.continued), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                mFragment.continueTimeAction();
            }
        });

        dialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.tofinish), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                getPresenter().stopAction();
                finish();
            }
        });
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();

        Button posiviveButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
        posiviveButton.setTextColor(Color.parseColor("#F79444"));
        Button negativeButton = dialog.getButton(DialogInterface.BUTTON_NEGATIVE);
        negativeButton.setTextColor(Color.parseColor("#000000"));
    }

    @Override
    public void onActionZhengFan(byte zhengfan, byte qingxie) {
        if (alertDialog != null) {
            alertDialog.dismiss();
        }
        String message = "";

        if (zhengfan == 0 && qingxie == 0) {
            // 戴反也戴斜了
            message = "设备戴反也戴斜了,请调整设备";
        } else if (zhengfan == 0 && qingxie == 1) {
            // 戴反了
            message = "设备戴反了,请调整设备";
        } else if (zhengfan == 1 && qingxie == 0) {
            // 戴斜了
            message = "设备戴斜了,请调整设备";
        } else if (zhengfan == 1 && qingxie == 1) {
            // 设备戴正确
            message = "设备佩戴正确,请开始运动吧";
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    alertDialog.dismiss();
                }
            }, 2000);
        }
        showDialog(message);
    }

    private Handler mHandler = new Handler();
    AlertDialog alertDialog;

    private void showDialog(String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(message);
        alertDialog = builder.show();
    }

    @Override
    public void finishActivity() {
        ArrayList<NewActionData> newActionDatas = getPresenter().getNewActionDatas();
        if (Constants.ACTION_NAME_ID1[mActionType] == ActionType.PBZC) {
            int time = 0;
            for (NewActionData actionData : newActionDatas) {
                int actionFlag = actionData.getActionFlag();
                if (actionFlag == 1) {
                    time += actionData.getTime();
                }
            }

            if (time >= 10000) {
                ActivitySwitcher.gotoNewShareActivity(this, newActionDatas);
            } else {
                finish();
            }
        } else {
            if (newActionDatas != null && newActionDatas.size() > 10) {
                ActivitySwitcher.gotoNewShareActivity(this, newActionDatas);
            } else {
                finish();
            }
        }
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Code.REQUEST_SUCCESS) {
            if (requestCode == 821) {
                mFragment.continueTimeAction();
            } else if (requestCode == 820) {
                finish();
            }
        }
    }

    public void playVoice(int voiceID) {
        if (voiceID != 0) {
            if (mMediaPlayer != null) {
                if (mMediaPlayer.isPlaying()) {
                    return;
                }

                mMediaPlayer.reset();
                mMediaPlayer.release();
                mMediaPlayer = null;
            }

            //播放音乐
            mMediaPlayer = new MediaPlayer();
            try {
                String packageName = MyApplication.getApplication().getPackageName();
                mMediaPlayer.setDataSource(NewActionActivity.this, Uri.parse("android.resource://" + packageName + "/" + voiceID));
                mMediaPlayer.prepareAsync();//异步准备
                mMediaPlayer.setOnPreparedListener(mOnPreparedListener);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private MediaPlayer.OnPreparedListener mOnPreparedListener = new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            mp.start();
        }
    };

    private void detachMediaPlayer() {
        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }
}
